package J3_31;

import java.util.Scanner;

public class thread {
    static class Counter1 {
        public int flag = 0;
    }
    public static void main1(String[] args) {
        Counter1 counter = new Counter1();
        Thread t1 = new Thread(() -> {
            while (counter.flag == 0) {
                // do nothing
            }
            System.out.println("循环结束!");
        });
        Thread t2 = new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            System.out.println("输⼊⼀个整数:");
            counter.flag = scanner.nextInt();
        });
        t1.start();
        t2.start();
    }
// 执⾏效果
// 当⽤⼾输⼊⾮0值时, t1 线程循环不会结束. (这显然是⼀个 bug)

    static class Counter {
        volatile public int count = 0;
        void increase() {
            count++;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        final Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter.count);
    }

}
